#define F_CPU 20000000UL  // 20 MHz CPU clock

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <avr/io.h>
#include <avr/interrupt.h>
#include <util/delay.h>

#include "serial.h"

// Global variables
Serialt serial;
uint8_t charIn; 								//USART incoming character
char str[20];
int isEnabled = 1; 
unsigned char ADCvalL, ADCvalH;

ISR (TIMER1_COMPB_vect) // Timer 1 is a 16-bit timer
{
	cli(); // Temporarily disable all interrupts
	
	TCNT1L = 0; // Reset timer
	TCNT1H = 0;

	PINC |= _BV(PC1); // Toggle output pin
	
	//if(isEnabled && (PORTD & _BV(PD7)) )
	//{	
	//	for(int i=0; str[i]; i++)
	//		serial_write(&serial, str[i]);
	//}

	sei(); // Re-enable interrupts
}

ISR (ADC_vect) // Analog conversion complete
{
	cli();
	
	// 	For ADLAR = 1
	ADCvalH = ADCH;
	//	if more precision is required, also read ADCL

	sprintf(str,"\n\rADCvalue: %d",(unsigned short int)ADCvalH);

	if(isEnabled)
	{
		// Send it out via serial here...
		for(int i=0; i<strnlen(str,15); i++)
			serial_write(&serial, str[i]);
	}

	sei();
}

void commMonitor(void)
{
	// Deal with incoming serial bytes here
	if (serial_read(&serial,&charIn)) //if there's data read it
	{
		serial_write(&serial, charIn); //echo it back out for now...
		switch (charIn)
		{
			case 'y':
				isEnabled = 1;
				break;
			case 'n':
				isEnabled = 0;
				break;
			default:
				break;
		}

	}

	return;
}


int main(void) 
{
	
	// Initialization

	
	// 	Set up serial port
	serial_init(&serial);
	
	//	Set up IO pin
	DDRC |= _BV(PC1); // set led pin to output direction
	PORTC |= _BV(PC1); // led on, pin high
	
	//	Set up timer
	TCCR1A |= _BV(5) | _BV(4); // Output compare mode, CTC mode, prescaler 1024, set flag to 1, channel B
	TCCR1B |= _BV(3) | _BV(2) | _BV(0); 
	OCR1BH = 0x4C; // Interrupt each time timer1 gets to this value (which ticks at 20.0Mhz / 1024 = 19.5 kHz)
	OCR1BL = 0x4B; // lower half of previous line. 0x4C4B is roughly 1 second per toggle	

	//	Set up A2D
	ADMUX |= _BV(5) | _BV(2) | _BV(0); // ADLAR=1, 0101 for ADC5
	ADCSRB |= _BV(2) | _BV(0); // ADC Auto Trigger source is Timer1 Compare Match B
	ADCSRA |= _BV(7) | _BV(5) | _BV(3) 
		| _BV(2) | _BV(1) | _BV(0); 	//	ADC Enable, auto-trigger enable, interrupt enable, prescaler 128

	// Start timer
	TCNT1H = 0; // Set timer top
	TCNT1L = 0; // Set timer bottom
	TIMSK1 |= _BV(2); // Enable timer interrupt OCIE1B

	sei(); // Globally enable interrupts
         
    while (1)                       /* loop forever */
    {
		commMonitor();	// Monitor serial port for incoming bytes
    }
	
	
	return 0;
}
